import cn.hutool.core.io.watch.WatchUtil;
import 算法.leetcode.TreeNode;

import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author: 谢君臣
 * @Date: 2021/11/18-10:30
 * @version: 1.0
 * @function:
 */
public class 最大路径和 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(-10);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(function(root));
    }
    static int function(TreeNode root){
        int max = 0;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            // 找到左子树最大路径
            int left = find(node.left);
            int right = find(node.right);
            max = Math.max(max,node.val+left+right);
            if (node.left!=null)
                queue.add(node.left);
            if (node.right!=null)
                queue.add(node.right);
        }
        return max;
    }

    static private int find(TreeNode node) {
        if (node==null)
            return 0;
        else {
            return node.val + Math.max(find(node.left),find(node.right));
        }
    }
}
